package com.example.lostandfoundsystem.services.common.model.base;

import gaarason.database.annotation.Column;
import gaarason.database.annotation.Primary;
import gaarason.database.contract.connection.GaarasonDataSource;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.support.FieldFill;
import gaarason.database.eloquent.Model;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.context.annotation.Lazy;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;

/**
 * @author lucifer
 * @since 2024-07-12-15:37
 */
@Data
@Accessors(chain = true)
public class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * auto generator start
     **/
    @Primary()
    @Column(name = "id", unsigned = true)
    private Long id;

    @Column(name = "created_at", nullable = true, selectable = false, fill = FieldFill.CreatedTimeFill.class)
    private LocalDateTime createdAt;

    @Column(name = "updated_at", nullable = true, selectable = false, fill = FieldFill.UpdatedTimeFill.class)
    private LocalDateTime updatedAt;

    /**
     * auto generator end
     **/
    public abstract static class BaseModel<T extends BaseEntity, K> extends Model<T, K> {
        @Resource
        @Lazy
        protected GaarasonDataSource gaarasonDataSource;

        @Override
        public GaarasonDataSource getGaarasonDataSource() {
            return gaarasonDataSource;
        }

        @Override
        public void log(String sql, Collection<?> parameterList) {
            String format = String.format(sql.replace(" ? ", "\"%s\""), parameterList.toArray());
            System.out.println(format);
        }

        @Override
        public boolean eventRecordCreating(Record<T, K> record) {
            record.getEntity().setUpdatedAt(LocalDateTime.now());
            return super.eventRecordCreating(record);
        }
    }
}
